package com.whfc.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * @Description: web工具类
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-12-03 10:15
 */
public class WebUtils {

    private static Logger logger = LoggerFactory.getLogger(WebUtils.class);

    public static final String X_FORWARDED_FOR = "x-forwarded-for";
    public static final String X_Real_IP = "X-Real-IP";

    public static final String USER_AGENT = "user-agent";


    /**
     * 打印cookie
     *
     * @param request
     */
    public static void logCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                logger.info("cookie,name:{},value:{}", cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge());
            }
        }
    }

    /**
     * 打印客户端IP
     *
     * @param request
     */
    public static void logClientIp(HttpServletRequest request) {
        logger.info("clientIp:{}", getClientIp(request));
    }

    /**
     * 打印客户端参数
     *
     * @param request
     */
    public static void logParams(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            logger.info("param,name:{},value:{}", entry.getKey(), entry.getValue());
        }
    }

    /**
     * 获取user-agent
     *
     * @param request
     * @return
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader(USER_AGENT);
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String clientIp = request.getHeader(X_FORWARDED_FOR);
        if (StringUtils.isEmpty(clientIp)) {
            clientIp = request.getHeader(X_Real_IP);
        }
        if (StringUtils.isEmpty(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }
}
